import NestedInteger from './NestedInteger'
/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * function NestedInteger() {
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     @return {boolean}
 *     this.isInteger = function() {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     @return {integer}
 *     this.getInteger = function() {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     @return {void}
 *     this.setInteger = function(value) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     @return {void}
 *     this.add = function(elem) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds, if it holds a nested list
 *     Return null if this NestedInteger holds a single integer
 *     @return {NestedInteger[]}
 *     this.getList = function() {
 *         ...
 *     };
 * };
 */

/**
 * @param {string} s
 * @return {NestedInteger}
 */
export var deserialize = function (s) {
  if (s[0] !== '[') {
    return new NestedInteger(parseInt(s))
  }
  const stack = [] // 一旦预[，则压入栈
  let num = '' // 存放数字
  let negative = false // 是否为负数
  for (let i = 0; i < s.length; i++) {
    const c = s[i]
    if (c === '[') {
      // 如果是[，则压入栈
      stack.push(new NestedInteger())
    } else if (c === '-') {
      // 如果是-，则设置负数标记
      negative = true
    } else if (isDigit(c)) {
      // 如果是数字，则存入num
      num += c
    } else if (c === ',' || c === ']') {
      if (num) {
        stack[stack.length - 1].add(new NestedInteger(negative ? -parseInt(num) : parseInt(num)))
        num = ''
        negative = false
      }
      if (c === ']' && stack.length > 1) {
        // 如果是]，则弹出栈
        const res = stack.pop()
        stack[stack.length - 1].add(res)
      }
    }
  }
  return stack.pop()
}

/**
 * 是否为数字
 * @param {*} ch
 * @returns {boolean}
 */
function isDigit(c) {
  return parseFloat(c).toString() === 'NaN' ? false : true
}

/**
 * s 实为json字符串，可转为对象。。
 * @param {string} s
 * @return {NestedInteger}
 */
export var deserialize2 = function (s) {
  let js = JSON.parse(s)
  let parse = function (value) {
    let res = new NestedInteger()

    if (Array.isArray(value)) {
      for (let i = 0; i < value.length; i++) {
        res.add(parse(value[i]))
      }
    } else {
      res.setInteger(value)
    }
    return res
  }
  return parse(js)
}
